<?php

namespace app\api\service;

use think\Request;

class Api extends \app\common\controller\Api
{
    public $noNeedLogin = '*';
    public $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /**
     * 设置价格
     */
    public function setPrice($price)
    {
        return $price * 10000;
    }

    /**
     * 获取价格
     */
    public function getPrice($price)
    {
        return $price / 10000;
    }

    /**
     * 日期时间转时间戳
     */
    public function dateToStamp($dateTime)
    {
        return strtotime($dateTime);
    }

    /**
     * 时间戳转日期时间
     */
    public function stampToDateTime($stamp)
    {
        return datetime($stamp, 'Y-m-d H:i:s');
    }

    /**
     * 获取年月日
     */
    public function stampToDate($stamp, $format = 'Ymd')
    {
        return datetime($stamp, $format);
    }

    /**
     * 获取产品编号
     */
    public function getProductNum()
    {
        return 'P'.datetime(time(), 'yhd').rand(1000, 9999);
    }

    /**
     * 获取订单编码
     */
    public function getNumId()
    {
        return 'RL'.date('ymdHi', time()).rand(1000, 9999);
    }

    /**
     * 获取指定日期N月后的日期
     */
    public function getNmonth($date, $n)
    {
        $time = strtotime('+'.$n.' month', strtotime($date));
        return datetime($time - 24 * 3600, 'Y-m-d 23:59:59');
    }

    /**
     * post请求
     */
    public function postUrl($url, $data){
        $data  = json_encode($data);
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }

    /**
     * 获取日期月份差
     */
    public function getMonthDiff($date1, $date2)
    {
        $date1 = date('Y-m-d', strtotime($date1));
        $date2 = date('Y-m-d', strtotime($date2));

        if (strtotime($date1) > strtotime($date2)) {
            $ymd = $date2;
            $date2 = $date1;
            $date1 = $ymd;
        }
        list($y1, $m1, $d1) = explode('-', $date1);
        list($y2, $m2, $d2) = explode('-', $date2);
        $y = $m = $d = $_m = 0;
        $math = ($y2 - $y1) * 12 + $m2 - $m1;
        $y = round($math / 12);
        $m = intval($math % 12);
        $d = (mktime(0, 0, 0, $m2, $d2, $y2) - mktime(0, 0, 0, $m2, $d1, $y2)) / 86400;
        if ($d < 0) {
            $m -= 1;
            $d += date('j', mktime(0, 0, 0, $m2, 0, $y2));
        }
        $m < 0 && $y -= 1;
        $m = $m < 0 ? 11 : $m;
        return array($y, $m, $d);
    }

}